/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.json.ir;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.errorprone.annotations.DoNotCall;
import io.trino.spi.block.Block;
import io.trino.spi.type.Type;

import java.util.Optional;

import static com.google.common.base.Preconditions.checkArgument;
import static io.trino.spi.predicate.Utils.nativeValueToBlock;
import static io.trino.spi.type.TypeUtils.readNativeValue;
import static java.util.Objects.requireNonNull;

public record IrLiteral(Optional<Type> type, Object value)
        implements IrPathNode
{
    public IrLiteral
    {
        requireNonNull(type, "type is null");
        checkArgument(type.isPresent(), "type is empty");
        requireNonNull(value, "value is null"); // (boxed) native representation. No null values allowed.
    }

    @JsonCreator
    @DoNotCall // For JSON deserialization only
    public static IrLiteral fromJson(@JsonProperty("type") Type type, @JsonProperty("valueAsBlock") Block value)
    {
        checkArgument(value.getPositionCount() == 1);
        return new IrLiteral(Optional.of(type), readNativeValue(type, value, 0));
    }

    @Override
    public <R, C> R accept(IrJsonPathVisitor<R, C> visitor, C context)
    {
        return visitor.visitIrLiteral(this, context);
    }

    @JsonProperty
    public Block getValueAsBlock()
    {
        return nativeValueToBlock(type().orElseThrow(), value);
    }
}
